package com.mini.rpc.provider.registry.loadbalancer;

import com.mini.rpc.common.ServiceMeta;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 负载均衡算法工厂类
 *
 * @author: hliushi
 * @date: 2022/4/24 9:39
 **/
public class LoadBalancerFactory {
    public static ConcurrentMap<String, ServiceLoadBalancer<ServiceMeta>>
            loadBalancerMap = new ConcurrentHashMap<>(10);

    static {
        loadBalancerMap.put(LoadBalancerType.ROUNDROBIN.name(), new RoundRobinLoadBalancer());
        loadBalancerMap.put(LoadBalancerType.RANDOM.name(), new RandomLoadBalancer());
        loadBalancerMap.put(LoadBalancerType.CONSISTENTHASH.name(), new ZKConsistentHashLoadBalancer());
        // todo bug点, ConcurrentHashMap 的key,value都不能为null
        // loadBalancerMap.put(LoadBalancerType.LEASTCONNECTION.name(), null);
    }

    /**
     * 根据参数类型获取对应的负载均衡算法
     *
     * @param type 负载均衡算法名称
     * @return ServiceLoadBalancer
     */
    public static ServiceLoadBalancer<ServiceMeta> getLoadBalancer(LoadBalancerType type) {
        // todo 负载均衡算法大小写问题
        // return loadBalancerMap.get(type.name().toUpperCase(Locale.ROOT));
        return loadBalancerMap.get(type.name());
    }
}
